<template>
  <div class="login">
    <h1>欢迎光临</h1>
    <h1>{{hospitalName}}</h1>
  </div>
</template>
<script>
import axios from 'axios';

const { config } = window;

export default {
  data() {
    return {
      hospitalName: sessionStorage.getItem('hosName') || '互联网医院', // 医院名称
      hospitalDomain: '', // 医院域名
      path: '', // 跳转参数
      pm: '',
      pms: '',
    };
  },
  beforeCreate() {
  },
  created() {
    console.log('--------------------------------------- login -------------------------------------------');

    // 获取参数
    this.pms = `${this.$route.query.pms}`;
    console.log(`---------- params: ${this.pms}`);

    this.path = `${this.pms.split('$$')[0]}`;
    this.pm = `${this.pms.split('$$')[1]}`;

    sessionStorage.setItem('pm', this.pm);

    // 判断是否直接支付
    // ?
  },
  mounted() {
    this.getToken();
    // window.document.title = `${sessionStorage.getItem('hosName')}`;
  },
  methods: {
    getToken() {
      if (sessionStorage.getItem('rybToken') == '' || sessionStorage.getItem('rybToken') == null) {
        // alert(`dlid的值 sesssion：${sessionStorage.getItem('APPID')}`);
        if (sessionStorage.getItem('APPID') != null && sessionStorage.getItem('APPID') != undefined && sessionStorage.getItem('APPID') != '') {
          // this.wxLogin(`${sessionStorage.getItem('APPID')}`);
          if (config.MODE == 'dev') {
            this.getUserInfoByDev();
          } else {
            this.wxLogin(`${sessionStorage.getItem('APPID')}`);
          }
        } else {
          this.$messagebox('登录提示', '网络连接超时请退出重新登录');
        }
      } else {
        /* this.$router.push('/yuyue/doctorpaiban'); */
        this.$router.push('/doctor/doctorlist');
      }
    },
    // 调试模式登录
    getUserInfoByDev() {
      axios.post(`${config.APIRootDev}/doctor/LocalDevLogin.dev?RYBID=PAT`).then((response) => {
        if (response.data.RESULT == '514' || response.data.RESULT == '515' || response.data.RESULT == '516') {
          this.$messagebox('登录失败', `${response.data.RESULTTEXT}`);
          return;
        }
        // 跳转到注册页
        if (response.data.RESULT == '513') {
          this.$router.push('/signup');
          return;
        }
        // 登陆成功后，初始化用户会话基本信息
        console.log(`--------- 登录时的用户信息: ${JSON.stringify(response.data)}`);
        sessionStorage.setItem('rybToken', response.data.rybToken);
        sessionStorage.setItem('patname', response.data.userInfo.nickname);
        sessionStorage.setItem('country', response.data.userInfo.country);
        sessionStorage.setItem('province', response.data.userInfo.province);
        sessionStorage.setItem('city', response.data.userInfo.city);
        sessionStorage.setItem('QrCodeTicketUrl', response.data.QrCodeTicketUrl);
        sessionStorage.setItem('headimgurl', response.data.userInfo.headimgurl);


        // 登录成功后，初始化应用全局参数
        this.$store.commit('setToken', 'token');
        // this.$store.login('state', response.data.rybToken);
        // this.QrCodeTicketUrl = response.data.QrCodeTicketUrl;
        /*
        console.log(`患者端sessionStorage.getItem('userInfo')   ${sessionStorage.getItem('userInfo')}`);
        console.log(`患者端sessionStorage中是否存储了rybToken:   ${sessionStorage.getItem('rybToken')}`);
        console.log(`患者端0sessionStorage中是否存储了QrCodeTicketUrl:   ${sessionStorage.getItem('QrCodeTicketUrl')}`);
        console.log(`患者端sessionStorage.getItem('userInfo.errCode')  ${response.data.userInfo.errCode}`);
        console.log(`患者端sessionStorage.getItem('userInfo.nickname')   ${response.data.userInfo.extReturn.nickname}`);
       */
        switch (this.path) {
          case 'feppay': // 前置机患者用户扫码支付
            this.$router.push('/fep/feppay');
            break;
          case 'jiaofei': // 用户点击支付缴费的消息模板进行支付
            this.$router.push('/chufang/prescribeRecord');
            break;
          case 'doctorpaiban': // 获取医生排信息
            this.$router.push('/yuyue/doctorpaiban/');
            break;
          case 'jiuzhen': // 查询就诊信息
            this.$router.push('/wode/jiuzhen/');
            break;
          case 'wode': // 进入我的页面
            this.$router.push('/wode/wode/');
            break;
          case 'yd': // 消息模板，获取医生排班信息 ？
            // this.$router.push({ name: 'check-yuyueDetailCheck', query: { pm: `${this.pm}` } });
            this.$router.push('/yuyue/doctorpaiban/');
            break;
          case 'cn': // 消息模板，?
            this.$router.push('/yuyue/doctorpaiban/');
            // this.$router.push({ name: 'check-nonePaymentCheck', query: { pm: `${this.pm}` } });
            break;
          case 'cu': // 消息模板，?
            this.$router.push('/yuyue/doctorpaiban/');
            // this.$router.push({ name: 'check-unshipCheck', query: { pm: `${this.pm}` } });
            break;
          case 'cp': // 消息模板，?
            this.$router.push('/yuyue/doctorpaiban/');
            // this.$router.push({ name: 'check-prescribeOrderDetailCheck', query: { pm: `${this.pm}` } });
            break;
          default:
            /* this.$router.push('/yuyue/doctorpaiban/'); */
            this.$router.push('/doctor/doctorlist');
        }
      }).catch((err) => {
        this.$messagebox('登录错误', `${JSON.stringify(err)}`);
        console.log(`登录错误信息: ${JSON.stringify(err)}`);
        window.location.href = `https://${sessionStorage.getItem('hospitalDomainname')}/nethospital/error`;
      });
    },
    // 静默方式请求CODE, 并返回到后台。如果后台通过CODE查询存储此OPENID, 直接返回TOKEN
    getUrlParam(name) { // ---返回的地址列表中获取CODE, name="code"
      console.log(`查看URL:${window.location}`);
      const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
      const r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    wxLogin(dlid) {
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${dlid}&redirect_uri=${window.location.href.split('#')[0]}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
      // let code = `${sessionStorage.getItem('code')}`;
      let code = this.getUrlParam('code');
      // alert(`code: ${code}`);

      if (!code) {
        code = sessionStorage.getItem('code');
        if (!code) {
          window.location = url;
        } else {
          sessionStorage.setItem('code', code);
          this.getUserInfo(code);
        }
      } else {
        sessionStorage.setItem('code', code);
        this.getUserInfo(code);
      }
    },
    getUserInfo(code) {
      console.log('--------------------------------------- 用户登录... -------------------------------------------'); // encodeURIComponent;
      // const redirectUri = `https://${this.$store.state.cookies.hospitalDomainname}/doctor/WeixinLogin.lg?reqType=login&RYBID=${config.APIAPPID}&DATA=${this.$store.state.cookies.hospitalDomainname}`;
      // const redirectUri1 = `https://${this.$store.state.cookies.hospitalDomainname}/doctor/WeixinLogin.lg`;
      // alert(`跳转请求后的连接地址： ${encodeURIComponent(redirectUri)}`);
      // alert(`dlid:    ${dlid}`);
      axios.post(`https://${sessionStorage.getItem('hospitalDomainname')}/doctor/WeixinLogin.lg?reqType=login&RYBID=${config.APIAPPID}&code=${code}&DATA=${sessionStorage.getItem('hospitalDomainname')}`).then((response) => {
      // axios.post(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${dlid}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`).then((response) => {
      // axios.get(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${dlid}&redirect_uri=${encodeURIComponent(redirectUri1)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`).then((response) => {
      /*
         * 不存在用户的情况：
         * "用户被禁"514
         * "手机验证失败"515
         * "身份证校验失败"515
         * "人脸验证失败"515
         * "待审核"515
         * "未审核通过"515
         * "该用户不存在"513 进行注册
         * "用户冗余"516
         */
        if (response.data.RESULT == '514' || response.data.RESULT == '515' || response.data.RESULT == '516') {
          this.$messagebox('登录失败', `${response.data.RESULTTEXT}`);
          return;
        }
        // 跳转到注册页
        if (response.data.RESULT == '513') {
          this.$router.push('/signup');
          return;
        }
        // 登陆成功后，初始化用户会话基本信息
        console.log(`--------- 登录时的用户信息: ${JSON.stringify(response.data)}`);
        sessionStorage.setItem('rybToken', response.data.rybToken);
        sessionStorage.setItem('patname', response.data.userInfo.nickname);
        sessionStorage.setItem('country', response.data.userInfo.country);
        sessionStorage.setItem('province', response.data.userInfo.province);
        sessionStorage.setItem('city', response.data.userInfo.city);
        sessionStorage.setItem('QrCodeTicketUrl', response.data.QrCodeTicketUrl);
        sessionStorage.setItem('headimgurl', response.data.userInfo.headimgurl);


        // 登录成功后，初始化应用全局参数
        this.$store.commit('setToken', 'token');
        // this.$store.login('state', response.data.rybToken);
        // this.QrCodeTicketUrl = response.data.QrCodeTicketUrl;
        /*
        console.log(`患者端sessionStorage.getItem('userInfo')   ${sessionStorage.getItem('userInfo')}`);
        console.log(`患者端sessionStorage中是否存储了rybToken:   ${sessionStorage.getItem('rybToken')}`);
        console.log(`患者端0sessionStorage中是否存储了QrCodeTicketUrl:   ${sessionStorage.getItem('QrCodeTicketUrl')}`);
        console.log(`患者端sessionStorage.getItem('userInfo.errCode')  ${response.data.userInfo.errCode}`);
        console.log(`患者端sessionStorage.getItem('userInfo.nickname')   ${response.data.userInfo.extReturn.nickname}`);
       */
        switch (this.path) {
          case 'feppay': // 前置机患者用户扫码支付
            this.$router.push('/fep/feppay');
            break;
          case 'doctor': // 用户点击支付缴费的消息模板进行支付
            // this.$router.push('/doctor/doctorlist');
            this.$router.push({
              name: 'doctor-doctorlist', query: { isshow: 1 },
            });
            break;
          case 'jiaofei': // 用户点击支付缴费的消息模板进行支付
            this.$router.push('/chufang/prescribeRecord');
            break;
          case 'doctorpaiban': // 获取医生排信息
            this.$router.push('/yuyue/doctorpaiban/');
            break;
          case 'jiuzhen': // 查询就诊信息
            this.$router.push('/wode/jiuzhen/');
            break;
          case 'wode': // 进入我的页面
            this.$router.push('/wode/wode/');
            break;
          case 'yd': // 消息模板，获取医生排班信息 ？
            // this.$router.push({ name: 'check-yuyueDetailCheck', query: { pm: `${this.pm}` } });
            this.$router.push('/yuyue/doctorpaiban/');
            break;
          case 'cn': // 消息模板，?
            this.$router.push('/yuyue/doctorpaiban/');
            // this.$router.push({ name: 'check-nonePaymentCheck', query: { pm: `${this.pm}` } });
            break;
          case 'cu': // 消息模板，?
            this.$router.push('/yuyue/doctorpaiban/');
            // this.$router.push({ name: 'check-unshipCheck', query: { pm: `${this.pm}` } });
            break;
          case 'cp': // 消息模板，?
            this.$router.push('/yuyue/doctorpaiban/');
            // this.$router.push({ name: 'check-prescribeOrderDetailCheck', query: { pm: `${this.pm}` } });
            break;
          default:
            /* this.$router.push('/yuyue/doctorpaiban/'); */
            this.$router.push('/doctor/doctorlist');
        }
      }).catch((err) => {
        this.$messagebox('登录错误', `${JSON.stringify(err)}`);
        console.log(`登录错误信息: ${JSON.stringify(err)}`);
        window.location.href = `https://${sessionStorage.getItem('hospitalDomainname')}/nethospital/error`;
      });
    },
  },
};
</script>
<style scoped>
.login {
  width: 100%;
  text-align: center;
}
.h1:first-child {
  color: #333;
  font-family: "微软雅黑";
  font-size: 3rem;
  margin: 0;
}
.h1:nth-child(2) {
  font-size: 5rem;
}
</style>

